/******************************************************************************
 * Copyright (C) 2011 ShenZhen ComTop Information Technology Co.,Ltd
 * All Rights Reserved.
 * 本软件为深圳康拓普开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、
 * 复制、修改或发布本软件.
 *****************************************************************************/

package com.code.common.systeminit;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import com.code.common.plugin.IPlugin;

/**
 * 初始化结束监听类
 * 
 * @author 周振兴
 * @since 1.0
 * @version 2011-5-20 周振兴
 */
public class ServerInitEndListener implements ServletContextListener {
    
    /** 日志对象 */
    private static final Logger LOGGER = LoggerFactory.getLogger(ServerInitEndListener.class);
    
    /** 插件集合 */
    private final List<IPlugin> plugins = new ArrayList<IPlugin>();
    
    /**
     * 服务器启动时调用
     * 
     * @param sce ServletContextEvent
     */
    public void contextInitialized(ServletContextEvent sce) {
        ApplicationContext objContext = EnviromentInfo.getWebApplicationContext();
        String[] strNames = objContext.getBeanNamesForType(IPlugin.class);
        for (String strName : strNames) {
            LOGGER.debug("加载插件:" + strName);
            try {
                IPlugin objPlugin = objContext.getBean(strName, IPlugin.class);
                objPlugin.init();
                objPlugin.execute();
                plugins.add(objPlugin);
            } catch (Throwable e) {
                LOGGER.error("加载插件{}时发生异常", strName, e);
            }
        }
    }
    
    /**
     * 服务器关闭时调用
     * 
     * @param sce ServletContextEvent
     */
    public void contextDestroyed(ServletContextEvent sce) {
        for (int i = 0; i < plugins.size(); i++) {
            IPlugin objPlugin = plugins.get(i);
            objPlugin.destory();
        }
    }
}